package priv.yiyuan.example.design.facade;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户服务外观
 * <p>
 * 外观模式-外观类
 * 观察者模式-具体主题
 *
 * @author YiYuan
 * @data 2025/9/13
 * @apoNote
 */
public class CustomerServiceFacade implements CustomerSubject {

    private CustomerRepository customerRepository;

    private List<CustomerObserver> observers = new ArrayList<>();

    public CustomerServiceFacade() {
        this.customerRepository = new CustomerRepository();
    }

    @Override
    public void addObserver(CustomerObserver observer) {
        observers.add(observer);
        System.out.println("观察者已添加: " + observer.getClass().getSimpleName());
    }

    @Override
    public void removeObserver(CustomerObserver observer) {
        observers.remove(observer);
        System.out.println("观察者已移除: " + observer.getClass().getSimpleName());
    }

    @Override
    public void notifyObserver(Customer customer) {
        System.out.println("通知所有观察者关于客户 " + customer.getId() + " 的更新...");
        for (CustomerObserver observer : observers) {
            observer.update(customer);
        }
    }

    public void updateCustomerLevel(String customerId, String newLevel) {
        System.out.println("\n--- 开始更新客户等级 ---");

        Customer customer = customerRepository.findById(customerId);

        if (customer != null) {
            String oldLevel = customer.getLevel();
            customer.setLevel(newLevel);
            customerRepository.save(customer);
            System.out.println("客户 " + customer.getName() + " 等级从 " + oldLevel + " 更新为 " + newLevel);
            this.notifyObserver(customer);
        }
        else {
            System.out.println("客户 " + customerId + " 未找到。");
        }

        System.out.println("---客户等级升级完成---\n");
    }

    public void addCustomer(Customer customer) {
        System.out.println("\n--- 添加新客户 ---");
        customerRepository.save(customer);
        System.out.println("新客户 " + customer.getName() + "已添加。");
        this.notifyObserver(customer);
        System.out.println("--- 新客户添加完成 ---\n");
    }
}
